package com.miage.ldapsec.obj;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class User {

    private String dn;
    private String login;
    private String commonName;
    private String surname;
    private String givenName;
    private String password;

    public User(String login, String surname, String givenName, String password) {
        this.dn = "uid=" + login + ",ou=people,o=root";
        this.login = login;
        this.commonName = surname + " " + givenName;
        this.surname = surname;
        this.givenName = givenName;
        if(!password.equals("") && password!=null) {
            this.password = encodePassword(password);
        }
    }

    public User() {
    }

    public String getDn() {
        return dn;
    }

    public void setDn(String dn) {
        this.dn = dn;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.dn = "uid=" + login + ",ou=people,o=root";
        this.login = login;
    }

    public String getCommonName() {
        return commonName;
    }

    public void setCommonName(String commonName) {
        this.commonName = commonName;
    }

    public String getGivenName() {
        return givenName;
    }

    public void setGivenName(String givenName) {
        this.commonName = surname + " " + givenName;
        this.givenName = givenName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = encodePassword(password);
    }
    
    private String encodePassword(String password) {

        byte[] uniqueKey = password.getBytes();
        byte[] hash = null;

        try {
            hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
        } catch (NoSuchAlgorithmException e) {
            throw new Error("No MD5 support in this VM.");
        }

        StringBuilder hashString = new StringBuilder();
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(hash[i]);
            if (hex.length() == 1) {
                hashString.append('0');
                hashString.append(hex.charAt(hex.length() - 1));
            } else {
                hashString.append(hex.substring(hex.length() - 2));
            }
        }
        return hashString.toString();
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.commonName = surname + " " + givenName;
        this.surname = surname;
    }

    @Override
    public String toString() {
        return dn;
    }
}